package cn.imvc.app.models;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.imvc.app.domains.ActivityType;
import cn.imvc.app.domains.GoodsState;
import cn.imvc.app.entities.Activity;
import cn.imvc.app.repositories.ActivityRepository;
import cn.imvc.app.repositories.GoodsSkuRepository;

@Service
public class ActivityModelImpl implements ActivityModel {

	@Autowired
	private ActivityRepository activityRepository;
	@Autowired
	private GoodsSkuRepository goodsSkuRepository;

	public List<Object[]> getActivitiesInfoByOrderAmount(Integer orderAmount) {
		List<Object[]> result = activityRepository.findAllSql("select *  from  ( select ac.* from  activity ac where ac.limitMoney<="+orderAmount+" and ac.startDate<=NOW() and ac.endDate>=NOW() and state =1 order by limitMoney desc ) a  group by type ");
		return result;
	}
	
	public List<Object[]> getGoodsInfoByActivityId(Integer activityId){
		if(activityId!=null&&activityId>0){
			Activity activity  = activityRepository.findOne(activityId);
			Byte activityType = null;
			if(activity!=null){
				activityType = activity.getType();
			}
			if(activityType!=null&&(byte)ActivityType.LARGESS.getCode()==activityType){//
				String skuIds = activity.getSkuId();
				if(StringUtils.isEmpty(skuIds)){
					skuIds =null;
				}else{
					char tem = skuIds.charAt(skuIds.length()-1);
					if(tem==','){
						skuIds = skuIds.substring(0, skuIds.length()-1);
					}
				}
				List<Object[]> result  = goodsSkuRepository.findAllSql("select g.id goods_id,sku.id sku_id,g.name,g.price,g.image from goods g , goods_sku sku  where g.id = sku.goodsId and sku.state="+GoodsState.GIFT_STATE.getCode()+" and sku.id in ("+skuIds+")");
				return result;
			}
		}
		return null;
	}

	public Activity getOne(Integer activityId) {
		if(activityId!=null&&activityId!=0){
			return activityRepository.getOne(activityId);
		}
		return null;
	}

	@Override
	public boolean checkIsValid(int goodsAmount, Integer activityId) {
		Activity activity = getOne(activityId);
		Byte state = activity.getState();
		int limitMoney =activity.getLimitMoney();
		long now = System.currentTimeMillis();
		long startTime = activity.getStartDate().getTime();
		long endTime = activity.getEndDate().getTime();
		return (state==1)&&(now>=startTime&&now<=endTime)&&(limitMoney<=goodsAmount);
	}
}
